package CA;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class InjectBugs {

	private final static String CrashSuperLocation= "C:/SignatureOutput/noscan/100/";
	
//	private final static String CrashSuperLocation= "C:/Users/Dan/workspace/CrashSignature/UnitTestData/missingStack/MissingStackFolder5/";
	
	private final int SuperErrorInjectRate = 70; // Every X number of lines that the information should be changed.
	
	
	public static void main(String[] args) throws IOException {
		InjectBugs ib = new InjectBugs();
		ib.Run();
	}
	
	
	private void Run() throws IOException
	{
	//	
		InsertMissingInformation(CrashSuperLocation, SuperErrorInjectRate);
		
	}	
		// make sure that it does not start with ^*^
		
		// Remove the first section of crash information
		public String removeFirstCrashInfoFromLine(String CrashInfo)
		{
			Helper h = new Helper();
			String retVal="";
			if (h.isMissingModule(CrashInfo)){ // check to see if the first crash information section is missing
				retVal=CrashInfo; // return what is passed ni
			}else{
				retVal="^*^";
				Pattern p = Pattern.compile("\\^\\*\\^");
				String[] items = p.split(CrashInfo);
				for (int i = 1; i < items.length; i++) {
					retVal+=items[i];
					if (i != items.length-1){ // Do not add value to last line
						retVal+="^*^";
					}
				}	  
			}
			
			return retVal;
		}

	public void InsertMissingInformation(String MainFolderLocation, int ErrorInjectRate){
		int IncrementTickCounter=0;
		int TotalLineCount=0;
		int TotalInjectFaultCount=0;
		File f0;
		
		Helper h = new Helper();
		List<String> AllFiles=new ArrayList<String>();	
		AllFiles=h.getAllFileNames(MainFolderLocation);
		for (int i = 0; i < AllFiles.size(); i++) {	 
			// Loop through every line of every file

			f0=new File(AllFiles.get(i));
			System.out.println(h.getFileLineCount(f0));
			TotalLineCount+=h.getFileLineCount(f0);
			
			// now loop through each line of the file that was created
			for (int ii = 0; ii < h.getFileLineCount(f0); ii++) {	
				IncrementTickCounter+=1;
				if (IncrementTickCounter>=ErrorInjectRate){ // should never exceed, but just added as a check
					// inject a fault
					h.setLineInformation(f0,removeFirstCrashInfoFromLine(h.getLineInformation(f0, ii)),ii);
					// setLineInformation(File file, String updatedText, int lineNumber) {
					IncrementTickCounter=0;
					TotalInjectFaultCount+=1;
				}else{
					
					// do nothing
				}
			}
			f0=null;
		}
		
		System.out.println("Total Line Count: " + TotalLineCount +". Inject fault count: " + TotalInjectFaultCount);

	}
		
}
